package com.zim.aliot.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.aliyuncs.utils.StringUtils;
import com.google.gson.Gson;
import com.zim.aliot.dao.CarsRepository;
import com.zim.aliot.dataobject.CarsDo;
import com.zim.aliot.enums.ResultEnum;
import com.zim.aliot.exception.IotApiException;
import com.zim.aliot.form.JoyCarsForm;
import com.zim.aliot.form.RtInfoForm;
import com.zim.aliot.service.CarsService;
import com.zim.aliot.util.ResultVOUtils;
import com.zim.aliot.vo.ResultVO;
import com.zim.aliot.vo.ReturnResultVO;
import com.zim.aliot.vo.VehicleVO;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/car")
@Slf4j
public class CarsController {
    
    @Autowired
    private CarsService CarsService;
    
    @Resource
    private RedisTemplate<String, VehicleVO> redisTemplate;
    
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    
    @Autowired
    private CarsRepository carsRepository;
    
    @Autowired
    private Gson gson;
    

    
    @RequestMapping(value = "/bindCar", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = "application/json;charset=UTF-8")
    public ResultVO<Object> bindCar(@Valid JoyCarsForm joyCarsForm,BindingResult bindingResult){
        if (bindingResult.hasErrors()) {
            log.error("【绑定】:参数不正确{}",joyCarsForm);
            throw new IotApiException(ResultEnum.PARAM_ERROR.getCode(),bindingResult.getFieldError().getDefaultMessage());
        }
    
       
	   boolean resBand = CarsService.bandCars(joyCarsForm.getSupplierNo(), joyCarsForm.getDeviceName(), joyCarsForm.getVin(), joyCarsForm.getCarSn());
	   if(resBand) {
		   CarsDo carsDo = new CarsDo();
	       carsDo.setDeviceName(joyCarsForm.getDeviceName());
	       carsDo.setSupplierNo(joyCarsForm.getSupplierNo());
	       carsDo.setVin(joyCarsForm.getVin());

	       CarsDo resCarsDo = CarsService.save(carsDo);
	       if(null == resCarsDo) { 
	    	   log.error("[ 车辆绑定数据保存失败 ]:{}",resCarsDo);
	           return ResultVOUtils.error(ResultEnum.WRITE_ERROR.getCode(),"绑定失败");
	       }else {
	           return ResultVOUtils.success("绑定成功");
	       }
	   }else {
		   return ResultVOUtils.error(ResultEnum.WRITE_ERROR.getCode(),"绑定失败");
	   }

    }
    
    @RequestMapping(value = "/unbindCar", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = "application/json;charset=UTF-8")
    public ResultVO<Object> unbindCar(@RequestParam(name = "deviceName",defaultValue="",required=true) String deviceName){
        CarsDo resCarsDo;
		try {
             resCarsDo = CarsService.find(deviceName);
           
        } catch (Exception e) {
            log.error("[查找数据]:{}",e.getMessage());
            return ResultVOUtils.error(ResultEnum.ERROR.getCode(),"设备不存在");
        }
		
		if(null != resCarsDo) {
			boolean res = CarsService.unBandCar(resCarsDo.getSupplierNo(), resCarsDo.getVin());
			if(res) {
				try {

					carsRepository.deleteById(resCarsDo.getDeviceName());
					
				} catch (Exception e) {
					log.error("[删除失败]:{}",e.getMessage());
			        return ResultVOUtils.error(ResultEnum.ERROR.getCode(),"解绑失败");
				}
				return ResultVOUtils.success("解绑成功");
			}else {
				return ResultVOUtils.error(ResultEnum.WRITE_ERROR.getCode(),"解绑失败");
			}
		}else {
			return ResultVOUtils.error(ResultEnum.ERROR.getCode(),"设备不存在");
		}
		

		
    }
    
    @RequestMapping(value = "/getRtInfo", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = "application/json;charset=UTF-8")
    public ReturnResultVO<Object> getRtInfo(@RequestParam("car_unique_id") String car_unique_id){
    	ReturnResultVO<Object> res = new ReturnResultVO<Object>();
    	if(StringUtils.isEmpty(car_unique_id)) {
    		res.setResult(1);
			res.setMsg("参数不能为空");
			return res;
    	}
    	List<VehicleVO> vehicleVOs = new ArrayList<>();
    	try {
    		List<String> keys = Arrays.asList(car_unique_id.split(","));
    		List<String> stringVehicleVO = stringRedisTemplate.opsForValue().multiGet(keys);
    		
    		for(String vehicleVO : stringVehicleVO) {
    			if(null != vehicleVO) {
    				
    				vehicleVOs.add(gson.fromJson(vehicleVO, VehicleVO.class));
    			}
    		}
    		res.setResult(0);
			res.setData(vehicleVOs);
			return res;
		} catch (Exception e) {
			log.error("【 获取实时数据 】:{}",e.getMessage());
			res.setResult(2);
			res.setMsg("查询失败");
			return res;
		}

    }
    
    @RequestMapping(value = "/getHisInfo", method = { RequestMethod.POST,
            RequestMethod.GET }, produces = "application/json;charset=UTF-8")
    public ReturnResultVO<Object> getHisInfo(@Valid RtInfoForm rtInfoForm,BindingResult bindingResult){
    	ReturnResultVO<Object> res = new ReturnResultVO<Object>();
    	if (bindingResult.hasErrors()) {
            log.error("【获取历史数据】:参数不正确{}",rtInfoForm);
            res.setResult(1);
			res.setMsg("参数不能为空");
			return res;
        }
    	
    	List<VehicleVO> vehicleVO = CarsService.getHisInfo(rtInfoForm.getCar_unique_id(), rtInfoForm.getTimeEnd()*1000, rtInfoForm.getTimeEnd()*1000);
    	if(vehicleVO != null) {
    		res.setResult(0);
			res.setData(vehicleVO);
			return res;
    	}else {
    		res.setResult(2);
			res.setMsg("查询失败");
			return res;
    	}

    }
}
